import { Component, OnInit } from "@angular/core";
import { AxiosService } from "../../axios.service";
import * as FileSaver from "file-saver";
import * as moment from "moment";
import { Workbook } from "exceljs";

@Component({
  selector: "app-zongjihua",
  templateUrl: "./zongjihua.component.html",
  styleUrls: ["./zongjihua.component.scss"],
})
export class ZongjihuaComponent implements OnInit {
  listOfData;

  // 判断每道工序是否delay
  isdelayDesign = [];
  isShowDesign = [];

  isdelayCode = [];
  isShowCode = [];

  isdelayJiagong = [];
  isShowJiagong = [];

  isdelayErci = [];
  isShowErci = [];

  isdelayZuzhuang = [];
  isShowZuzhuang = [];

  downList: any[];
  constructor(public axios: AxiosService) { }

  ngOnInit(): void {
    this.getData();
  }

  // 请求数据
  getData() {
    this.axios
      .axiosPost("QueryProductionSchedulingPlan")
      .then((data) => {
        this.listOfData = data["order"];
        this.listOfData.sort((a, b) => {
          return a.delivery_date > b.delivery_date ? 1 : -1;
        });
        // for (let i = 0; i < this.listOfData.length; i++) {
        //   // 判断delay
        //   // 设计
        //   if (new Date(this.listOfData[i].design_qixian).getTime() < new Date(this.listOfData[i].design_endtime).getTime()) {
        //     this.isdelayDesign.push(true);
        //     this.isShowDesign.push(false);
        //   } else if (new Date(this.listOfData[i].design_qixian).getTime() >= new Date(this.listOfData[i].design_endtime).getTime() || this.listOfData[i].design_qixian === '' || this.listOfData[i].design_endtime === '') {
        //     this.isdelayDesign.push(false);
        //     this.isShowDesign.push(true);
        //   }
        //   // 编程
        //   if (new Date(this.listOfData[i].code_qixian).getTime() < new Date(this.listOfData[i].code_endtime).getTime()) {
        //     this.isdelayCode.push(true);
        //     this.isShowCode.push(false);
        //   } else if (new Date(this.listOfData[i].code_qixian).getTime() >= new Date(this.listOfData[i].code_endtime).getTime() || this.listOfData[i].code_qixian === '' || this.listOfData[i].code_endtime === '') {
        //     this.isdelayCode.push(false);
        //     this.isShowCode.push(true);
        //   }
        //   // 加工
        //   if (new Date(this.listOfData[i].jiagong_qixian).getTime() < new Date(this.listOfData[i].jiagong_endtime).getTime()) {
        //     this.isdelayJiagong.push(true);
        //     this.isShowJiagong.push(false);
        //   } else if (new Date(this.listOfData[i].jiagong_qixian).getTime() >= new Date(this.listOfData[i].jiagong_endtime).getTime() || this.listOfData[i].jiagong_qixian === '' || this.listOfData[i].jiagong_endtime === '') {
        //     this.isdelayJiagong.push(false);
        //     this.isShowJiagong.push(true);
        //   }
        //   // 二次加工
        //   if (new Date(this.listOfData[i].ercijg_qixian).getTime() < new Date(this.listOfData[i].ercijg_endtime).getTime()) {
        //     this.isdelayErci.push(true);
        //     this.isShowErci.push(false);
        //   } else if (new Date(this.listOfData[i].ercijg_qixian).getTime() >= new Date(this.listOfData[i].ercijg_endtime).getTime() || this.listOfData[i].ercijg_qixian === '' || this.listOfData[i].ercijg_endtime === '') {
        //     this.isdelayErci.push(false);
        //     this.isShowErci.push(true);
        //   }
        //   // 组装
        //   if (new Date(this.listOfData[i].zuzhuang_qixian).getTime() < new Date(this.listOfData[i].zuzhuang_endtime).getTime()) {
        //     this.isdelayZuzhuang.push(true);
        //     this.isShowZuzhuang.push(false);
        //   } else if (new Date(this.listOfData[i].zuzhuang_qixian).getTime() >= new Date(this.listOfData[i].zuzhuang_endtime).getTime() || this.listOfData[i].zuzhuang_qixian === '' || this.listOfData[i].zuzhuang_endtime === '') {
        //     this.isdelayZuzhuang.push(false);
        //     this.isShowZuzhuang.push(true);
        //   }
        // }
        console.log(this.listOfData);
      })
      .catch((err) => {
        console.log(err);
      });
  }

  // 下载
  downLoad() {
    // this.axios.axiosPost("AddDownloadCount")
    //   .then((data) => {
    //     console.log(data);
    //   })
    //   .catch((err) => {
    //     console.log(err);
    //   });
    let exportlist = [];
    console.log(this.listOfData.length);
    if (this.listOfData.length == 0) {
      alert("暫無數據");
    } else {
      for (let i = 0; i < this.listOfData.length; i++) {
        exportlist.push({
          狀態: this.listOfData[i].status,
          廠別: this.listOfData[i].factory,
          機種: this.listOfData[i].machine_type,
          治具名稱: this.listOfData[i].name,
          數量: this.listOfData[i].quatity,
          治具交期: this.listOfData[i].delivery_date,
          申請人: this.listOfData[i].apply_person,
          工聯單號: this.listOfData[i].unionorder,
          "设计期限（计划）": this.listOfData[i].design_qixian,
          "设计期限（实际）": this.listOfData[i].design_endtime,
          "cnc加工期限（计划）": this.listOfData[i].jiagong_qixian,
          "cnc加工期限（实际）": this.listOfData[i].jiagong_endtime,
          "二次加工期限（计划）": this.listOfData[i].ercijg_qixian,
          "二次加工期限（实际）": this.listOfData[i].ercijg_endtime,
          "组装期限（计划）": this.listOfData[i].zuzhuang_qixian,
          "组装期限（实际）": this.listOfData[i].zuzhuang_endtime,
        });
      }
      console.log(exportlist);
      this.downList = [];
      exportlist.forEach((row: any) => {
        this.downList.push(Object.values(row));
      });
      let head = [
        "狀態",
        "廠別",
        "機種",
        "治具名稱",
        "數量",
        "治具交期",
        "申請人",
        "工聯單號",
        "设计期限（计划）",
        "设计期限（实际）",
        "cnc加工期限（计划）",
        "cnc加工期限（实际）",
        "二次加工期限（计划）",
        "二次加工期限（实际）",
        "组装期限（计划）",
        "组装期限（实际）",
      ];
      let reportData = {
        title: "生产排程总计划",
        headers: head,
        data: this.downList,
      };
      this.saveAsExcelFile(reportData);
    }
  }

  private saveAsExcelFile(excelData) {
    const title = excelData.title;
    const header = excelData.headers;
    const data = excelData.data;

    const workbook = new Workbook();
    const worksheet = workbook.addWorksheet("生产排程总计划");
    const headerRow = worksheet.addRow(header);
    const worksheet1 = workbook.getWorksheet(1);
    console.log(worksheet1);

    headerRow.eachCell((cell) => {
      cell.fill = {
        type: "pattern",
        pattern: "solid",
        // 设置表头背景颜色
        fgColor: { argb: "FFFFFF" },
      };
      cell.alignment = { vertical: "middle", horizontal: "center" };
      cell.font = {
        bold: true,
        // 设置表头的字体颜色
        color: { argb: "000000" },
        size: 12,
      };
      cell.border = {
        // 设置边框粗细
        top: { style: "thin" },
        left: { style: "thin" },
        bottom: { style: "thin" },
        right: { style: "thin" },
      };
    });
    // 设置表格内容居中对齐
    const contentarray = [];
    data.forEach((ele) => {
      contentarray.push(worksheet.addRow(ele));
    });
    // tslint:disable-next-line: prefer-for-of
    for (let i = 0; i < contentarray.length; i++) {
      contentarray[i].eachCell((cell) => {
        cell.border = {
          // 设置边框粗细
          top: { style: "thin" },
          left: { style: "thin" },
          bottom: { style: "thin" },
          right: { style: "thin" },
        };
        cell.fill = {
          type: "pattern",
          pattern: "solid",
          // 设置表头背景颜色
          fgColor: { argb: "FFFFFF" },
        };
        cell.alignment = { vertical: "middle", horizontal: "center" };
      });
    }

    worksheet.getColumn(1).width = 8;
    worksheet.getColumn(2).width = 12;
    worksheet.getColumn(3).width = 18;
    worksheet.getColumn(4).width = 55;
    worksheet.getColumn(5).width = 12;
    worksheet.getColumn(6).width = 12;
    worksheet.getColumn(7).width = 9;
    worksheet.getColumn(8).width = 21;
    worksheet.getColumn(9).width = 20;
    worksheet.getColumn(10).width = 20;
    worksheet.getColumn(11).width = 23;
    worksheet.getColumn(12).width = 23;
    worksheet.getColumn(13).width = 24;
    worksheet.getColumn(14).width = 24;
    worksheet.getColumn(15).width = 20;
    worksheet.getColumn(16).width = 20;

    workbook.xlsx.writeBuffer().then((result) => {
      const blob = new Blob([result], {
        type:
          "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=UTF-8",
      });
      FileSaver.saveAs(
        blob,
        title + "_" + moment().format("YYYYMMDDHHmmss") + ".xlsx"
      );
    });
  }
}
